package com.hyg.module_report.ui.customView;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;


import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.module_report.R;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Random;


/**
 * <p>
 * Description：不带动画的百分比数据类型饼状统计图
 * </p>
 *
 * @author panfu
 */
public class PercentPieView extends View {

    /**
     * 中心坐标
     */
    private int centerX;
    private int centerY;

    //使用wrap_content时默认的尺寸
    public static final int DEFAULT_WIDTH = 300;
    public static final int DEFAULT_HEIGHT = 300;

    /**
     * 半径
     */
    private float radius;

    /**
     * 弧形外接矩形
     */
    private RectF rectF;

    /**
     * 中间文本的大小
     */
    private Rect centerTextBound = new Rect();

    /**
     * 数据文本的大小
     */
    private Rect dataTextBound = new Rect();

    /**
     * 扇形画笔
     */
    private Paint mArcPaint;

    /**
     * 中心文本画笔
     */
    private Paint centerTextPaint;

    /**
     * 数据画笔
     */
    private Paint dataPaint;

    /**
     * 数据源数字数组
     */
    private ArrayList<Float> numbers = new ArrayList<>();

    /**
     * 数据源名称数组
     */
    private ArrayList<String> names = new ArrayList<>();
    private ArrayList<String> CheckNames = new ArrayList<>();

    /**
     * 数据源总和
     */
    private int sum;

    /**
     * 颜色数组
     */
    private ArrayList<Integer> colors = new ArrayList<>();

    private Random random = new Random();

    //自定义属性 Start

    /**
     * 中间字体大小
     */
    private float centerTextSize = 50;

    /**
     * 数据字体大小
     */
    private float dataTextSize = 40f;

    /**
     * 中间字体颜色
     */
//    private int centerTextColor = Color.parseColor("#7b40be");
    private int centerTextColor = Color.parseColor("#666666");

    /**
     * 数据字体颜色
     */
    private int dataTextColor = Color.parseColor("#36444E");

    /**
     * 圆圈的宽度
     */
    private float circleWidth = 150;

    /*  画布平移量 */
    private float translateX = 0f;

    /*  文字间排布所在Y轴 */
    private float TextPaddingY = 0f;
    private float TextPaddingX = 0f;

    private Paint SmallCriclePaint ;

    //自定义属性 End

    public PercentPieView(Context context) {
        super(context);
        init();
    }

    public PercentPieView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PercentPieView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PieView);
        centerTextSize = typedArray.getDimension(R.styleable.PieView_centerTextSize, centerTextSize);
        dataTextSize = typedArray.getDimension(R.styleable.PieView_dataTextSize, dataTextSize);
        circleWidth = typedArray.getDimension(R.styleable.PieView_circleWidth, circleWidth);
        centerTextColor = typedArray.getColor(R.styleable.PieView_centerTextColor, centerTextColor);
        dataTextColor = typedArray.getColor(R.styleable.PieView_dataTextColor, dataTextColor);
        typedArray.recycle();
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        centerTextSize = 0;
        mArcPaint = new Paint();
        mArcPaint.setStrokeWidth(circleWidth);
        mArcPaint.setAntiAlias(true);
        mArcPaint.setStyle(Paint.Style.FILL);


        centerTextPaint = new Paint();
        centerTextPaint.setTextSize(centerTextSize);
        centerTextPaint.setAntiAlias(true);
        centerTextPaint.setStyle(Paint.Style.FILL);
        centerTextPaint.setColor(centerTextColor);

        dataPaint = new Paint();
        dataPaint.setStrokeWidth(2);
        dataPaint.setTextSize(dataTextSize);
        dataPaint.setAntiAlias(true);
        dataPaint.setColor(dataTextColor);

        SmallCriclePaint = new Paint();
        SmallCriclePaint.setAntiAlias(true);

//        numbers.add(32.75f);
//        numbers.add(7.90f);
//        numbers.add(8.89f);
//        numbers.add(6.29f);
//        numbers.add(9.88f);
//        numbers.add(12.71f);
//        numbers.add(7.95f);
//        numbers.add(8.73f);
//        numbers.add(4.91f);

        numbers.add(28.9f);
        numbers.add(16.4f);
        numbers.add(5.2f);
        numbers.add(6.29f);
        numbers.add(10.2f);
        numbers.add(13.2f);
        numbers.add(8.0f);
        numbers.add(8.8f);
        numbers.add(2.5f);

        names.add("平和质");
        names.add("阳虚质");
        names.add("阴虚质");
        names.add("痰湿质");
        names.add("湿热质");
        names.add("气虚质");
        names.add("血瘀质");
        names.add("气郁质");
        names.add("特禀质");

        colors.add(Color.parseColor("#BDDB97"));
        colors.add(Color.parseColor("#EE9D35"));
        colors.add(Color.parseColor("#F4B2AA"));
        colors.add(Color.parseColor("#A7DAE4"));
        colors.add(Color.parseColor("#A48DC1"));
        colors.add(Color.parseColor("#F9D29E"));
        colors.add(Color.parseColor("#D96BA3"));
        colors.add(Color.parseColor("#818BC4"));
        colors.add(Color.parseColor("#7DC6A7"));
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measureWidthSize = MeasureSpec.getSize(widthMeasureSpec);
        int measureHeightSize = MeasureSpec.getSize(heightMeasureSpec);
        int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
        int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);
        if (measureWidthMode == MeasureSpec.AT_MOST
                && measureHeightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
        } else if (measureWidthMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(DEFAULT_WIDTH, measureHeightSize);
        } else if (measureHeightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(measureWidthSize, DEFAULT_HEIGHT);
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        centerX = getMeasuredWidth() / 2;
        centerY = getMeasuredHeight() / 2;
        //设置半径为宽高最小值的1/4
        radius = Math.min(getMeasuredWidth(), getMeasuredHeight()) / 4;
        float bili = getMeasuredWidth() / 1080f;
        dataTextSize = bili * 38f;
        dataPaint.setTextSize(dataTextSize);
//       如果设置 mArcPaint.setStyle(Paint.Style.FILL); 后，设置宽度无效
//        circleWidth = bili * 320f;
//        mArcPaint.setStrokeWidth(circleWidth);
        //设置扇形外接矩形
        rectF = new RectF(centerX - radius *1.7f,
                centerY - radius * 1.7f,
                centerX + radius * 1.7f,
                centerY + radius * 1.7f );

        TextPaddingY = getMeasuredHeight() / 10;
        TextPaddingX = centerX + radius * 2.1f;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        calculateAndDraw(canvas);
    }

    /**
     * 计算比例并且绘制扇形和数据
     */
    private void calculateAndDraw(Canvas canvas) {
        translateX = 0 - (centerX - radius * 1.8f);
        canvas.translate(translateX, 0);
        if (numbers == null || numbers.size() == 0) {
            return;
        }
        //扇形开始度数
        int startAngle = 0;
        //所占百分比
        float percent;
        //所占度数
        float angle;
        for (int i = 0; i < numbers.size(); i++) {
            percent = numbers.get(i) / 100;
            //获取百分比在360中所占度数
            if (i == numbers.size() - 1) {//保证所有度数加起来等于360
                angle = 360 - startAngle;
            } else {
                angle = (float) Math.ceil(percent * 360);
            }
            //绘制第i段扇形
            drawArc(canvas, startAngle, angle, colors.get(i));
            startAngle += angle;

            //绘制数据
            if (numbers.get(i) <= 0) {
                continue;
            }
            //当前弧线中心点相对于纵轴的夹角度数,由于扇形的绘制是从三点钟方向开始，所以加90
            float arcCenterDegree = 90 + startAngle - angle / 2;
            for(int j = 0; j < CheckNames.size(); j++){
                if(CheckNames.get(j).equals(names.get(i))){
                    drawData(canvas, arcCenterDegree, i, percent);

                }
            }
            ArrayTextAndCricle(canvas,i);
        }
        //绘制中心数字总和
//        canvas.drawText(sum + "", centerX - centerTextBound.width() / 2, centerY + centerTextBound.height() / 2, centerTextPaint);
    }

    public void ArrayTextAndCricle(Canvas canvas, int num){

        SmallCriclePaint.setAlpha(255);
        SmallCriclePaint.setColor(colors.get(num));
        canvas.drawCircle(TextPaddingX,TextPaddingY + TextPaddingY * num , getResources().getDimension(R.dimen.font8) , SmallCriclePaint);
        canvas.drawText(names.get(num) , TextPaddingX + getResources().getDimension(R.dimen.font8) * 1.5f,
                TextPaddingY + TextPaddingY * num + getResources().getDimension(R.dimen.font8) * 0.5f, dataPaint);
    }

    /**
     * 计算每段弧度的中心坐标
     *
     * @param degree 当前扇形中心度数
     */
    private float[] calculatePosition(float degree) {
        //由于Math.sin(double a)中参数a不是度数而是弧度，所以需要将度数转化为弧度
        //而Math.toRadians(degree)的作用就是将度数转化为弧度
        //sin 一二正，三四负 sin（180-a）=sin(a)
        //扇形弧线中心点距离圆心的x坐标
        float x = (float) (Math.sin(Math.toRadians(degree)) * radius * 1.3);
        //cos 一四正，二三负
        //扇形弧线中心点距离圆心的y坐标
        float y = (float) (Math.cos(Math.toRadians(degree)) * radius * 1.3);

        //每段弧度的中心坐标(扇形弧线中心点相对于view的坐标)
        float startX = centerX + x;
        float startY = centerY - y;

        float[] position = new float[2];
        position[0] = startX;
        position[1] = startY;
        return position;
    }

    private float[] RadianEdge(float degree ,float radiuNum) {
        //由于Math.sin(double a)中参数a不是度数而是弧度，所以需要将度数转化为弧度
        //而Math.toRadians(degree)的作用就是将度数转化为弧度
        //sin 一二正，三四负 sin（180-a）=sin(a)
        //扇形弧线中心点距离圆心的x坐标
        float x = (float) (Math.sin(Math.toRadians(degree)) * radius * radiuNum);
        //cos 一四正，二三负
        //扇形弧线中心点距离圆心的y坐标
        float y = (float) (Math.cos(Math.toRadians(degree)) * radius * radiuNum);

        //每段弧度的外边缘坐标(扇形弧线中心点相对于view的坐标)
        float startX = centerX + x;
        float startY = centerY - y;

        float[] position = new float[2];
        position[0] = startX;
        position[1] = startY;
        return position;
    }

    /**
     * 绘制数据
     *
     * @param canvas  画布
     * @param degree  第i段弧线中心点相对于纵轴的夹角度数
     * @param i       第i段弧线
     * @param percent 数据百分比
     */
    private void drawData(Canvas canvas, float degree, int i, float percent) {
        //弧度中心坐标
        float startX = calculatePosition(degree)[0];
        float startY = calculatePosition(degree)[1];

        //获取名称文本大小
        dataPaint.getTextBounds(names.get(i), 0, names.get(i).length(), dataTextBound);
        //绘制名称数据，20为纵坐标偏移量
        canvas.drawText(names.get(i),
                startX - dataTextBound.width() / 2,
                startY + dataTextBound.height() / 2 - 20,
                dataPaint);


        //拼接百分比并获取文本大小
        DecimalFormat df = new DecimalFormat("0.0");
        String percentString = df.format(percent * 100) + "%";
        dataPaint.getTextBounds(percentString, 0, percentString.length(), dataTextBound);

        //绘制百分比数据，20为纵坐标偏移量
        canvas.drawText(percentString,
                startX - dataTextBound.width() / 2,
                startY + dataTextBound.height() * 2 - 20,
                dataPaint);


        float RadianX = RadianEdge(degree,1.6f)[0];
        float RadianY = RadianEdge(degree,1.6f)[1];
        float RadianX1 = RadianEdge(degree + (float) 3.2,1.75f)[0];
        float RadianY1 = RadianEdge(degree + (float) 3.2,1.75f)[1];
        float RadianX2 = RadianEdge(degree - (float) 3.2,1.75f)[0];
        float RadianY2 = RadianEdge(degree - (float) 3.2,1.75f)[1];
        //想画三角形
        Path mPath = new Path();
        mPath.reset();
        mPath.moveTo(RadianX, RadianY);
        mPath.lineTo(RadianX1 , RadianY1 );
        mPath.lineTo(RadianX2 , RadianY2 );
        mPath.close();
//        centerTextPaint.setColor(colors.get(i));
        canvas.drawPath(mPath, centerTextPaint);

    }

    /**
     * 绘制扇形
     *
     * @param canvas     画布
     * @param startAngle 开始度数
     * @param angle      扇形的度数
     * @param color      颜色
     */
    private void drawArc(Canvas canvas, float startAngle, float angle, int color) {
        mArcPaint.setColor(color);
        //+0.5是为了让每个扇形之间没有间隙
        if (angle != 0) {
            angle += 0.6f;
        }
        canvas.drawArc(rectF, startAngle, angle, true, mArcPaint);
    }

    /**
     * 生成随机颜色
     */
    private int randomColor() {
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);
        return Color.rgb(red, green, blue);
    }

    public void setData(ArrayList<String> name){
        if(!Utils.isEmpty(name)){
            CheckNames = name;
        }
        invalidate();
    }
    /**
     * 设置数据(使用随机颜色)
     *
     * @param numbers 数字数组
     * @param names   名称数组
     */
    public void setData(ArrayList<Float> numbers, ArrayList<String> names) {
        if (numbers == null || numbers.size() == 0
                || names == null || names.size() == 0) {
            return;
        }
        if (numbers.size() != names.size()) {
            return;
        }
        this.numbers = numbers;
        this.names = names;
        for (int i = 0; i < numbers.size(); i++) {
            colors.add(Color.WHITE);
        }
        sum = 0;
        for (int i = 0; i < this.numbers.size(); i++) {
            //计算总和
            sum += numbers.get(i);
            //随机颜色
            colors.set(i, randomColor());
        }
        //计算总和数字的宽高
        centerTextPaint.getTextBounds(sum + "", 0, (sum + "").length(), centerTextBound);
        invalidate();
    }

    /**
     * 设置数据(自定义颜色)
     *
     * @param numbers 数字数组
     * @param names   名称数组
     * @param colors  颜色数组
     */
    public void setData(ArrayList<Float> numbers, ArrayList<String> names, ArrayList<Integer> colors) {
        if (numbers == null || numbers.size() == 0
                || names == null || names.size() == 0
                || colors == null || colors.size() == 0) {
            return;
        }
        if (numbers.size() != names.size() || numbers.size() != colors.size()) {
            return;
        }
        this.numbers = numbers;
        this.names = names;
        this.colors = colors;
        sum = 0;
        for (int i = 0; i < this.numbers.size(); i++) {
            //计算总和
            sum += numbers.get(i);
        }
        //计算总和数字的宽高
        centerTextPaint.getTextBounds(sum + "", 0, (sum + "").length(), centerTextBound);
        invalidate();
    }
}
